package com.qili.controller.adminManager.jc;

import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseDict;
import com.qili.entity.base.BaseMilepostJc;
import com.qili.entity.base.BaseStageJc;
import com.qili.exception.MyException;
import com.qili.service.base.BaseDictService;
import com.qili.service.base.BaseMilepostJcService;
import com.qili.service.base.BaseStageJcService;
import com.qili.util.JsonUtil;
import com.qili.util.ReType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Auther qiguoqing
 * @Date 2020/11/18
 * @Version
 */
@Slf4j
@Controller
@RequestMapping("/adminManager/jc/milepostManagerJc")
public class milepostManagerJcController {
    @Autowired
    BaseDictService baseDicService;
    @Autowired
    BaseMilepostJcService baseMilepostService;
    @Autowired
    BaseStageJcService baseStageService;
    @GetMapping(value = "index")
    @RequiresPermissions("milepost:show")
    public String showStage(Model model, HttpServletRequest request) {
        List<BaseDict> PTYPEList = baseDicService.selectByTypeCode("PTYPE001JC");
        model.addAttribute("PTYPEList", PTYPEList);
        return "/adminManager/jc/milepostManagerJc/milepost";
    }

    /**
     * 检测阶段里程配置 - 项目类型新增页面
     * @param model
     * @param request
     * @param baseStage
     * @return
     */
    @GetMapping(value = "addType")
    @RequiresPermissions("jcType:add")
    public String addType(Model model, HttpServletRequest request, BaseStageJc baseStage) {
        BaseStageJc stage = baseStageService.selectByPrimaryKey(baseStage.getId());
        model.addAttribute("stage",stage);
        return "/adminManager/jc/milepostManagerJc/add_type";
    }

    /**
     * 项目阶段新增页面
     * @param model
     * @param request
     * @return
     */
    @GetMapping(value = "addStage")
    @RequiresPermissions("jcStage:add")
    public String addStage(Model model,HttpServletRequest request) {
        List<BaseDict> JDlist = baseDicService.selectByTypeCode("JD001JC");
//        List<BaseDict> PTYPEList = baseDicService.selectByTypeCode("PTYPE001");
        model.addAttribute("JDlist", JDlist);
//        model.addAttribute("PTYPEList", PTYPEList);
        return "/adminManager/jc/milepostManagerJc/add_stage";
    }

    /**
     * 项目里程新增页面
     * @param model
     * @param request
     * @param baseStage
     * @return
     */
    @GetMapping(value = "addMilepost")
    @RequiresPermissions("jcMilestone:add")
    public String addMilepost(Model model,HttpServletRequest request,BaseStageJc baseStage) {
        String  ss=request.getParameter("id");
        System.out.println(  baseStage.getId()+"......................");
        List<BaseDict> LCList = baseDicService.selectByTypeCode("LC001JC");
        LCList.forEach(dict -> {
            //设计和方案添加(设计阶段)
            if(StringUtils.isNotBlank(dict.getBadtLevel2())){
                String oldBadtName = dict.getBadtName();
                dict.setBadtName(oldBadtName+"("+dict.getBadtLevel2()+")");
            }
        });
        BaseStageJc stage = baseStageService.selectByPrimaryKey(baseStage.getId());
        model.addAttribute("stage",stage);
        model.addAttribute("LCList", LCList);
        return "/adminManager/jc/milepostManagerJc/add_milepost";
    }

    /**
     * 项目类型编辑页面
     * @param model
     * @param request
     * @param baseDict
     * @return
     */
    @GetMapping(value = "updateType")
    @RequiresPermissions("jcType:edit")
    public String UpdateType(Model model,HttpServletRequest request,BaseDict baseDict) {
        BaseDict type = baseDicService.selectByPrimaryKey(baseDict.getBadtNo());
        model.addAttribute("type",type);
        return "/adminManager/jc/milepostManagerJc/update_type";
    }

    /**
     * 项目阶段编辑页面
     * @param model
     * @param request
     * @param baseStage
     * @return
     */
    @GetMapping(value = "updateStage")
    @RequiresPermissions("jcStage:edit")
    public String UpdateStage(Model model,HttpServletRequest request,BaseStageJc baseStage) {
        List<BaseDict> JDlist = baseDicService.selectByTypeCode("JD001JC");
        BaseStageJc stage = baseStageService.selectByPrimaryKey(baseStage.getId());
        model.addAttribute("JDlist", JDlist);
        model.addAttribute("stage",stage);
        return "/adminManager/jc/milepostManagerJc/update_stage";
    }

    /**
     * 项目里程编辑页面
     * @param model
     * @param request
     * @param baseMilepost
     * @return
     */
    @GetMapping(value = "updateMilepost")
    @RequiresPermissions("jcMilestone:edit")
    public String UpdateMilepost(Model model,HttpServletRequest request,BaseMilepostJc baseMilepost) {
        List<BaseDict> LCList = baseDicService.selectByTypeCode("LC001JC");
        BaseMilepostJc milepost = baseMilepostService.selectByPrimaryKey(baseMilepost.getId());
        model.addAttribute("milepost",milepost);
        model.addAttribute("LCList", LCList);
        return "/adminManager/jc/milepostManagerJc/update_milepost";
    }

    @GetMapping(value = "showEditGuide")
    @ApiOperation(value = "/showEditGuide", httpMethod = "GET", notes = "显示里程指南编辑页面")
    public String showEditGuide(Model model){
        return "/ueditor/editor";
    }

    @ResponseBody
    @RequestMapping(value = "/getGuide", method = RequestMethod.GET)
    public String getGuideByBadtNo(String badtNo) {
        try {
            BaseDict baseDict = baseDicService.selectByPrimaryKey(badtNo);
            return baseDict.getBadtLevel9();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getMilefileGuideLen", method = RequestMethod.GET)
    public JsonUtil getMilefileGuideLen(String mileFileType) {
        JsonUtil jsonUtil = new JsonUtil();
        try {
            if(StringUtils.isBlank(mileFileType)){
                jsonUtil.setFlag(false);
                jsonUtil.setMsg("没有需要查询的文件");
                return jsonUtil;
            }
            BaseDict selectBaseDict = new BaseDict();
            selectBaseDict.setBadtTypecode(DictTypes.WJ.getType());
            selectBaseDict.setBadtCode(mileFileType);
            Map guideTextLenMap = baseDicService.getGuideTextLen(selectBaseDict);
            jsonUtil.setFlag(true);
            jsonUtil.setData(guideTextLenMap);
            return jsonUtil;
        } catch (Exception e) {
            e.printStackTrace();
            jsonUtil.setFlag(false);
            jsonUtil.setMsg("系统出错");
            return jsonUtil;
        }
    }


    /**
     * 删除里程指南
     * @param baseDict
     * @return
     */
    @ApiOperation(value = "/deleteGuideFromDict", httpMethod = "POST", notes = "删除里程指南")
    @PostMapping(value = "deleteGuideFromDict")
    @ResponseBody
    public JsonUtil deleteGuideFromDict(BaseDict baseDict){
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(false);
        if(baseDict == null || StringUtils.isBlank(baseDict.getBadtCode()) || StringUtils.isBlank(baseDict.getBadtTypecode())){
            jsonUtil.setMsg("没有需要删除的指南");
            return jsonUtil;
        }
        baseDicService.deleteGuideFromDict(baseDict);
        jsonUtil.setFlag(true);
        return jsonUtil;
    }

    /**
     * 获取字典中的指南
     * @param baseDict
     * @return
     */
    @ApiOperation(value = "/getGuideFromDict", httpMethod = "GET", notes = "获取存在字典中的指南")
    @GetMapping(value = "getGuideFromDict")
    @ResponseBody
    public JsonUtil getGuideFromDict(BaseDict baseDict){
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(false);
        if(baseDict == null || StringUtils.isBlank(baseDict.getBadtCode()) || StringUtils.isBlank(baseDict.getBadtTypecode())){
            jsonUtil.setMsg("没有需要查询的指南");
            return jsonUtil;
        }
        List<BaseDict> select = baseDicService.select(baseDict);
        if(select == null || select.size() == 0){
            jsonUtil.setMsg("没有需要查询的指南");
            return jsonUtil;
        }
        jsonUtil.setFlag(true);
        jsonUtil.setData(select.get(0).getBadtLevel9());
        return jsonUtil;
    }

    /**
     * 更新里程指南
     * @param baseDict
     * @return
     */
    @ApiOperation(value = "/updateGuideDict", httpMethod = "POST", notes = "更新字典里的指南")
    @PostMapping(value = "updateGuideDict")
    @ResponseBody
    public JsonUtil updateGuideDict(BaseDict baseDict){
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(false);
        if(baseDict == null || StringUtils.isBlank(baseDict.getBadtCode()) || StringUtils.isBlank(baseDict.getBadtTypecode())){
            jsonUtil.setMsg("没有需要保存的指南");
            return jsonUtil;
        }
        if(StringUtils.isBlank(baseDict.getBadtLevel9())){
            return deleteGuideFromDict(baseDict);
        }
        baseDicService.updateMilepostGuide(baseDict);
        jsonUtil.setFlag(true);
        return jsonUtil;
    }


    @ApiOperation(value = "/typeList", httpMethod = "GET", notes = "项目类型编号")
    @GetMapping(value = "typeList")
    @ResponseBody
    public ReType selectByProjectTypeNo(Model model, String page, String limit, HttpServletResponse response) {
        ReType AlLevel = new ReType();
        try {
            //分页
//            com.github.pagehelper.Page<BaseDict> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<BaseDict> AlstData = baseDicService.selectByTypeCode("PTYPE001JC");
//            AlLevel.setCount(tPage.getTotal());
            AlLevel.setData(AlstData);
            AlLevel.setCode(0);
        } catch (NumberFormatException e) {
            AlLevel.setMsg("查询异常！！" + e.getMessage());
            AlLevel.setCode(1);
            e.printStackTrace();
        }

        return AlLevel;
    }
    @ApiOperation(value = "/stageList", httpMethod = "GET", notes = "项目阶段")
    @GetMapping(value = "stageList")
    @ResponseBody
    public ReType selectStage(BaseStageJc baseStage,Model model, String page, String limit) {
        ReType AlLevel = new ReType();
        try {
            //分页
//            com.github.pagehelper.Page<BaseStageJc> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<BaseStageJc> baseStageList=baseStageService.selectBaseStageListByProjectTypeNo(baseStage.getProjectTypeNo(),DictTypes.JDJC.getType());
//            AlLevel.setCount(tPage.getTotal());
            AlLevel.setData(baseStageList);
            AlLevel.setCode(0);
        } catch (NumberFormatException e) {
            AlLevel.setMsg("查询异常！！" + e.getMessage());
            AlLevel.setCode(1);
            e.printStackTrace();
        }
        return AlLevel;
    }
    @ApiOperation(value = "/milepostList", httpMethod = "GET", notes = "项目里程")
    @GetMapping(value = "milepostList")
    @ResponseBody
    public ReType selectMilepost(BaseMilepostJc baseMilepost, Model model, String page, String limit) {
        ReType AlLevel = new ReType();
        try {
            //分页
//            com.github.pagehelper.Page<BaseMilepostJc> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
//            List<BaseMilepostJc> AlstData = baseMilepostService.select(baseMilepost);
            List<BaseMilepostJc> baseMilepostList = baseMilepostService.selectMilepostListByStageId(baseMilepost.getStageId(),DictTypes.PROJECT_MILEPOST_JC.getType());
//            AlLevel.setCount(tPage.getTotal());
            AlLevel.setData(baseMilepostList);
            AlLevel.setCode(0);
        } catch (NumberFormatException e) {
            AlLevel.setMsg("查询异常！！" + e.getMessage());
            AlLevel.setCode(1);
            e.printStackTrace();
        }
        return AlLevel;
    }

    /**
     * 检测阶段里程配置 - 项目类型新增
     * @param baseDict
     * @return
     */
    @ApiOperation(value = "/addTypeValue", httpMethod = "POST", notes = "增加项目类型")
    @PostMapping(value = "addTypeValue")
    @ResponseBody
    @RequiresPermissions("jcType:add")
    public JsonUtil addType(BaseDict baseDict) {
        JsonUtil json = new JsonUtil();
        json.setFlag(false);
        if (baseDict.getBadtName().isEmpty()) {
            json.setFlag(false);
            json.setMsg("获取数据失败!!!");
            return json;
        }
        baseDict.setBadtTypecode(DictTypes.PROJECT_TYPEJC.getType());
        List<BaseDict> exitedBaseDict = baseDicService.select(baseDict);
        if(exitedBaseDict.size() > 0){
            json.setFlag(false);
            json.setMsg("已经存在的项目类型");
            return json;
        }
        try {
            //查询项目类型字典当前最大值
//            String badtCode = baseMilepostService.selectBadtCode();
            String badtCode = baseDicService.selectMaxCodeByTypeCode(DictTypes.PROJECT_TYPEJC.getType());
            if (StringUtils.isBlank(badtCode)){
                json.setMsg("没有最大值!!!");
                baseDict.setBadtCode("001");
            }else {
               String next =  getNextValue(badtCode);
               baseDict.setBadtCode(next);
            }
            baseDicService.insert(baseDict);
        } catch (MyException e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("添加失败!!!"+e.getMessage());
            return json;
        }
        json.setFlag(true);
        json.setMsg("添加成功");
        return json;
    }

    /**
     * 项目阶段新增
     * @param baseStage
     * @return
     */
    @ApiOperation(value = "/addStageValue", httpMethod = "POST", notes = "增加项目阶段")
    @PostMapping(value = "addStageValue")
    @ResponseBody
    @RequiresPermissions("jcStage:add")
    public JsonUtil addStage(BaseStageJc baseStage) {
        JsonUtil json = new JsonUtil();
        json.setFlag(false);
        if (baseStage == null) {
            json.setFlag(false);
            json.setMsg("获取数据失败!!!");
            return json;
        }
        try {
            //判断是否存在
            boolean ifExited = baseStageService.ifExited(baseStage);
            if(ifExited){
                json.setFlag(false);
                json.setMsg("已经存在的项目阶段!");
                return json;
            }
            baseStage.setCreateTime(new Date());
            baseStageService.insert(baseStage);
        } catch (MyException e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("添加失败!!!"+e.getMessage());
            return json;
        }
        json.setFlag(true);
        json.setMsg("添加成功");
        return json;
    }


    /**
     * 项目里程新增
     * @param baseMilepost
     * @return
     */
    @ApiOperation(value = "/addMilepostValue", httpMethod = "POST", notes = "增加项目里程")
    @PostMapping(value = "addMilepostValue")
    @ResponseBody
    @RequiresPermissions("jcMilestone:add")
    public JsonUtil addMilepost(BaseMilepostJc baseMilepost) {
        JsonUtil json = new JsonUtil();
        json.setFlag(false);
        if (baseMilepost == null) {
            json.setFlag(false);
            json.setMsg("获取数据失败!!!");
            return json;
        }
        //验证是否存在
        boolean ifExited = baseMilepostService.ifExited(baseMilepost);
        if(ifExited){
            json.setFlag(false);
            json.setMsg("已经存在的里程");
            return json;
        }
        try {
            baseMilepostService.insert(baseMilepost);
        } catch (MyException e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("添加失败!!!"+e.getMessage());
            return json;
        }
        json.setFlag(true);
        json.setMsg("添加成功");
        return json;
    }

    /**
     * 更新项目类型
     * @param baseDict
     * @return
     */
    @ApiOperation(value = "/updateTypeValue", httpMethod = "POST", notes = "更新项目类型")
    @PostMapping(value = "updateTypeValue")
    @ResponseBody
    @RequiresPermissions("jcType:edit")
    public JsonUtil updateTypeValue(BaseDict baseDict) {
        JsonUtil json = new JsonUtil();
        json.setFlag(false);
        if (baseDict == null) {
            json.setFlag(false);
            json.setMsg("获取数据失败!!!");
            return json;
        }
        boolean ifExited = baseDicService.ifExited(baseDict.getBadtTypecode(), baseDict.getBadtName());
        if(ifExited){
            json.setFlag(false);
            json.setMsg("已经存在的项目类型");
            return json;
        }
        try {
            baseDicService.updateByPrimaryKeySelective(baseDict);
        } catch (MyException e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("操作失败!!!"+e.getMessage());
            return json;
        }
        json.setFlag(true);
        json.setMsg("操作成功");
        return json;
    }

    /**
     * 更新项目阶段
     * @param baseStage
     * @return
     */
    @ApiOperation(value = "/updateStageValue", httpMethod = "POST", notes = "更新项目类型")
    @PostMapping(value = "updateStageValue")
    @ResponseBody
    @RequiresPermissions("jcStage:edit")
    public JsonUtil updateStageValue(BaseStageJc baseStage) {
        JsonUtil json = new JsonUtil();
        json.setFlag(false);
        if (baseStage == null) {
            json.setFlag(false);
            json.setMsg("获取数据失败!!!");
            return json;
        }
        boolean canEdit = baseStageService.checkCanEdit(baseStage);
        if(!canEdit){
            json.setFlag(false);
            json.setMsg("已经存在的项目阶段！");
            return json;
        }
        try {
            baseStageService.updateByPrimaryKeySelective(baseStage);
        } catch (MyException e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("操作失败!!!"+e.getMessage());
            return json;
        }
        json.setFlag(true);
        json.setMsg("操作成功");
        return json;
    }

    /**
     * 项目里程编辑
     * @param baseMilepost
     * @return
     */
    @ApiOperation(value = "/updateMilepostValue", httpMethod = "POST", notes = "更新里程")
    @PostMapping(value = "updateMilepostValue")
    @ResponseBody
    @RequiresPermissions("jcMilestone:edit")
    public JsonUtil updateMilepostValue(BaseMilepostJc baseMilepost) {
        JsonUtil json = new JsonUtil();
        json.setFlag(false);
        if (baseMilepost == null) {
            json.setFlag(false);
            json.setMsg("获取数据失败!!!");
            return json;
        }
        boolean canEdit = baseMilepostService.checkCanEdit(baseMilepost);
        if(!canEdit){
            json.setFlag(false);
            json.setMsg("已经存在的项目里程！");
            return json;
        }
        try {
            baseMilepostService.updateByPrimaryKeySelective(baseMilepost);
        } catch (MyException e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("操作失败!!!"+e.getMessage());
            return json;
        }
        json.setFlag(true);
        json.setMsg("操作成功");
        return json;
    }
    @ApiOperation(value = "/delType", httpMethod = "POST", notes = "删除项目类型")
    @PostMapping(value = "delType")
    @ResponseBody
    public JsonUtil delType(@RequestParam("badtNo") String badtNo) {
        JsonUtil json  = new JsonUtil();
        try {
            int Aires = baseDicService.deleteByPrimaryKey(badtNo);
            if (Aires > 0) {
                json.setFlag(true);
            } else {
                json.setFlag(false);
                json.setMsg("数据库返回更新失败!!!");
            }
        }catch (Exception e){
            json.setFlag(false);
            json.setMsg("执行异常!!!"+e.getMessage());
        }
        return json;
    }

    /**
     * 删除项目阶段
     * @param id
     * @return
     */
    @ApiOperation(value = "/delStage", httpMethod = "POST", notes = "删除项目阶段")
    @PostMapping(value = "delStage")
    @ResponseBody
    @RequiresPermissions("jcStage:delete")
    public JsonUtil delStage(String id) {
        JsonUtil json  = new JsonUtil();
        if(StringUtils.isBlank(id)){
            log.error("删除项目阶段时,id为空");
            json.setFlag(false);
            json.setMsg("删除失败");
        }
        try {
            BaseMilepostJc delMilepost = new BaseMilepostJc();
            delMilepost.setStageId(id);
            baseMilepostService.delete(delMilepost);
            baseStageService.delStage(id);
        }catch (Exception e){
            json.setFlag(false);
            json.setMsg("执行异常!!!"+e.getMessage());
        }
        return json;
    }

    /**
     * 删除项目里程
     * @param id
     * @return
     */
    @ApiOperation(value = "/delMilepost", httpMethod = "POST", notes = "删除项目里程")
    @PostMapping(value = "delMilepost")
    @ResponseBody
    @RequiresPermissions("jcMilestone:delete")
    public JsonUtil delMilepost(String id) {
        JsonUtil json  = new JsonUtil();
        if(StringUtils.isBlank(id)){
            log.error("删除项目里程时,id为空");
            json.setFlag(false);
            json.setMsg("删除失败");
            return json;
        }
        try {
            baseMilepostService.deleteByPrimaryKey(id);
        }catch (Exception e){
            json.setFlag(false);
            json.setMsg("执行异常!!!"+e.getMessage());
        }
        json.setFlag(true);
        return json;
    }
    /***
     *
     * @param val  当前序列值
     * @return 返回下一个序列
     */
    public static String getNextValue(String val) {
        int next = Integer.valueOf(val) + 1;
        String res = "";
        int length = (next + "").length();
        switch (length) {
            case 1:
                res = "00" + next;
                break;
            case 2:
                res = "0" + next;
                break;
            default:
                res = "" + next;
                break;
        }
        return res;
    }

}
